import { _decorator, Component, Node, math, game } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EyeController')
export class EyeController extends Component {
    @property(Node)
    eyeLeft: Node = null;

    @property(Node)
    eyeRight: Node = null;

    private _isRunning: boolean = true;
    private _eyeStartY: number = 0;
    private _originalEyeScale: number = 1;

    // 眨眼相关
    private _blinkTimer: number = 0;
    private _isBlinking: boolean = false;
    private _blinkDuration: number = 0.1;
    private _nextBlinkTime: number = 2;

    onLoad() {
        this._eyeStartY = this.eyeLeft.position.y;
        this._originalEyeScale = this.eyeLeft.scale.y;
    }

    public set running(val: boolean) {
        this._isRunning = val;
        if (!val) {
            this.resetEyeScale();
            this.updateEyeAngle(0);
        }
    }

    update(deltaTime: number) {
        if (!this._isRunning) return;
        const realDeltaTime = game.deltaTime;
        this.updateBlink(realDeltaTime);
    }

    public updateEyeAngle(angle: number) {
        const radians = math.toRadian(angle);
        const direction = new math.Vec2(Math.cos(radians), Math.sin(radians));

        const ellipseA = 10;
        const ellipseB = 8;
        const eyeSpacing = 25;

        const xOffset = direction.x * ellipseA;
        const yOffset = direction.y * ellipseB;

        this.eyeLeft.setPosition(xOffset - (eyeSpacing / 2), this._eyeStartY + yOffset);
        this.eyeRight.setPosition(xOffset + (eyeSpacing / 2), this._eyeStartY + yOffset);
    }

    private updateBlink(deltaTime: number) {
        if (this._isBlinking) {
            this._blinkTimer += deltaTime;
            const progress = this._blinkTimer / this._blinkDuration;
            
            if (progress <= 0.5) {
                const scale = math.lerp(this._originalEyeScale, 0.1, progress * 2);
                this.setEyeScale(scale);
            } else {
                const scale = math.lerp(0.1, this._originalEyeScale, (progress - 0.5) * 2);
                this.setEyeScale(scale);
            }

            if (progress >= 1) {
                this._isBlinking = false;
                this._blinkTimer = 0;
                this._nextBlinkTime = 2 + Math.random() * 3;
                this.resetEyeScale();
            }
        } else {
            this._nextBlinkTime -= deltaTime;
            if (this._nextBlinkTime <= 0) {
                this.startBlink();
            }
        }
    }

    private startBlink() {
        this._isBlinking = true;
        this._blinkTimer = 0;
    }

    private setEyeScale(scale: number) {
        this.eyeLeft.setScale(1, scale);
        this.eyeRight.setScale(1, scale);
    }

    private resetEyeScale() {
        this.setEyeScale(this._originalEyeScale);
    }
} 